<template>
  <div class="download-manager">
    <div class="header">
      <div class="left">
        <el-button-group>
          <el-button 
            type="primary" 
            @click="copyDownloadFolderPath"
            :icon="Document"
          >
            复制下载目录
          </el-button>
          <el-button 
            type="success" 
            @click="fetchDownloadList(true)"
            :loading="loading"
            :icon="Refresh"
          >
            刷新列表
          </el-button>
        </el-button-group>
      </div>
      <div class="right">
        <el-button-group>
          <el-button 
            type="warning" 
            @click="handleClearCompleted"
            :disabled="!hasCompletedDownloads"
          >
            清理已完成
          </el-button>
          <el-button 
            type="danger" 
            @click="handleClearAll"
            :disabled="downloadList.length === 0"
          >
            清空列表
          </el-button>
        </el-button-group>
      </div>
    </div>

    <el-table
      :data="downloadList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      :row-class-name="getRowClassName"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="封面" width="120">
        <template #default="{ row }">
          <el-image 
            :src="getProxyImageUrl(row.cover)" 
            :preview-src-list="row.cover ? [getProxyImageUrl(row.cover)] : []"
            fit="cover"
            style="width: 160px; height: 90px"
            @error="handleImageError"
          />
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" min-width="300">
        <template #default="{ row }">
          <div class="video-title">
            <span>{{ row.title }}</span>
            <el-tag 
              v-if="row.folderName" 
              size="small" 
              type="info"
              class="folder-tag"
            >
              {{ row.folderName }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="progress" label="进度" width="200">
        <template #default="{ row }">
          <div class="progress-info">
            <el-progress 
              :percentage="row.progress" 
              :status="getProgressStatus(row.status)"
            />
            <div class="progress-details" v-if="isDownloading(row.status)">
              <span>{{ formatFileSize(row.downloadedSize) }}/{{ formatFileSize(row.fileSize) }}</span>
              <span>{{ formatSpeed(row.speed) }}</span>
              <span>{{ formatRemainingTime(row.remainingTime) }}</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button
              v-if="row.status === 'failed'"
              type="warning" 
              size="small"
              @click="handleRetryDownload(row)"
              :icon="Refresh"
            >
              重试
            </el-button>
            <el-button 
              type="danger" 
              size="small"
              @click="handleDeleteDownload(row)"
              :icon="Delete"
            >
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Folder, 
  FolderOpened, 
  Delete, 
  Refresh, 
  Warning,
  Document
} from '@element-plus/icons-vue'
import { 
  getDownloadList, 
  getDownloadFolderPath,
  openDownloadFolder, 
  retryDownload, 
  deleteDownload, 
  clearCompletedDownloads,
  apiMethods
} from '../utils/api'
import axios from 'axios'
import { useRoute } from 'vue-router'
import { watch } from 'vue'

// 定义事件
const emit = defineEmits(['switch-tab'])

const loading = ref(false)
const downloadList = ref([])
const selectedDownloads = ref([])
const downloadFolderPath = ref('') // 存储实际的下载路径

// 计算属性：活跃下载数量
const activeDownloads = computed(() => {
  return downloadList.value.filter(item => 
    ['preparing', 'downloading', '正在下载', '正在下载音频', '正在合并文件'].includes(item.status)
  ).length
})

// 计算属性：是否有已完成的下载
const hasCompletedDownloads = computed(() => {
  return downloadList.value.some(item => item.status === 'completed')
})

// 获取下载目录路径
const fetchDownloadFolderPath = async () => {
  try {
    const response = await axios.get('/api/video/download/folder-path')
    downloadFolderPath.value = response.data
  } catch (error) {
    console.error('获取下载目录路径失败:', error)
    ElMessage.error('获取下载目录路径失败: ' + (error.response?.data?.message || error.message))
  }
}

// 获取下载列表
const fetchDownloadList = async (showMessage = false) => {
  try {
    loading.value = true
    const response = await axios.get('/api/video/download/list')
    downloadList.value = response.data
    
    if (showMessage) {
      ElMessage.success('刷新成功')
    }
  } catch (error) {
    console.error('获取下载列表失败:', error)
    ElMessage.error('获取下载列表失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 获取状态对应的类型
const getStatusType = (status) => {
  const statusMap = {
    'preparing': 'info',
    'downloading': 'primary',
    '正在下载': 'primary',
    '正在下载音频': 'primary',
    '正在合并文件': 'warning',
    'completed': 'success',
    'failed': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态效果
const getStatusEffect = (status) => {
  return isDownloading(status) ? 'light' : 'dark'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'preparing': '准备中',
    'downloading': '下载中',
    '正在下载': '下载中',
    '正在下载音频': '下载音频',
    '正在合并文件': '合并中',
    'completed': '已完成',
    'failed': '失败'
  }
  return statusMap[status] || status
}

// 获取进度条状态
const getProgressStatus = (status) => {
  if (status === 'failed') return 'exception'
  if (status === 'completed') return 'success'
  return ''
}

// 判断是否正在下载
const isDownloading = (status) => {
  return ['preparing', 'downloading', '正在下载', '正在下载音频', '正在合并文件'].includes(status)
}

// 获取行类名
const getRowClassName = ({ row }) => {
  if (row.status === 'completed') return 'completed-row'
  if (row.status === 'failed') return 'failed-row'
  if (isDownloading(row.status)) return 'downloading-row'
  return ''
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes || bytes === 0) return '未知'
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let size = bytes
  let unitIndex = 0
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024
    unitIndex++
  }
  return `${size.toFixed(2)} ${units[unitIndex]}`
}

// 格式化下载速度
const formatSpeed = (bytesPerSecond) => {
  if (!bytesPerSecond || bytesPerSecond === 0) return '0 B/s'
  const units = ['B/s', 'KB/s', 'MB/s', 'GB/s']
  let speed = bytesPerSecond
  let unitIndex = 0
  while (speed >= 1024 && unitIndex < units.length - 1) {
    speed /= 1024
    unitIndex++
  }
  return `${speed.toFixed(2)} ${units[unitIndex]}`
}

// 格式化剩余时间
const formatRemainingTime = (seconds) => {
  if (!seconds || seconds === 0) return ''
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)
  
  if (hours > 0) {
    return `${hours}h ${minutes}m ${secs}s`
  } else if (minutes > 0) {
    return `${minutes}m ${secs}s`
  } else {
    return `${secs}s`
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}

// 获取代理图片URL
const getProxyImageUrl = (url) => {
  if (!url) return ''
  // 如果已经是代理URL，直接返回
  if (url.startsWith('/api/')) return url
  // 否则转换为代理URL
  return `/api/video/image?url=${encodeURIComponent(url)}`
}

// 获取默认封面
const getDefaultCover = () => {
  return '/api/video/image?url=' + encodeURIComponent('https://i0.hdslb.com/bfs/archive/1c4717964a42b83890f3b4c8c6c5c5c5c5c5c5c5.jpg')
}

// 打开下载目录
const handleOpenDownloadFolder = () => {
  try {
    const pathToOpen = downloadFolderPath.value?.resolvedPath || downloadFolderPath.value?.absolutePath || getDefaultDownloadPath()
    console.log('打开下载目录:', { pathToOpen, downloadFolderPath: downloadFolderPath.value })
    openFolderWithFallback(pathToOpen, '下载')
  } catch (error) {
    console.error('打开下载目录失败:', error)
    const pathToShow = downloadFolderPath.value?.resolvedPath || downloadFolderPath.value?.absolutePath || getDefaultDownloadPath()
    fallbackOpenFolderWithMessage(pathToShow, '下载')
  }
}

// 获取默认下载路径
const getDefaultDownloadPath = () => {
  const platform = navigator.platform.toLowerCase()
  if (platform.includes('win')) {
    return 'C:\\Users\\' + (process.env.USERNAME || '用户名') + '\\Downloads\\BilibiliDownloader'
  } else if (platform.includes('mac')) {
    return '/Users/' + (process.env.USER || '用户名') + '/Downloads/BilibiliDownloader'
  } else {
    return '/home/' + (process.env.USER || '用户名') + '/Downloads/BilibiliDownloader'
  }
}

// 打开视频文件夹
const handleOpenVideoFolder = async (video) => {
  try {
    // 获取实际的下载路径
    const basePath = downloadFolderPath.value?.resolvedPath || 
                    downloadFolderPath.value?.absolutePath || 
                    downloadFolderPath.value || 
                    '';
    
    // 构建完整的文件夹路径：基础路径 + 大标题 + 视频标题，使用 Windows 路径分隔符
    const folderPath = `${basePath}\\${video.folderName || ''}\\${video.title}`;
    console.log('尝试打开文件夹:', folderPath);
    
    const response = await axios.post('/api/video/download/open-folder', {
      path: folderPath
    });
    
    if (response.data.success) {
      ElMessage.success('已打开文件夹');
    } else {
      ElMessage.warning('无法打开文件夹，请手动打开');
    }
  } catch (error) {
    console.error('打开文件夹失败:', error);
    const errorMessage = error.response?.data?.message || error.message || '未知错误';
    ElMessage.error(`打开文件夹失败: ${errorMessage}`);
  }
};

// 复制视频文件夹路径
const copyVideoFolderPath = async (video) => {
  try {
    // 获取实际的下载路径
    const basePath = downloadFolderPath.value?.resolvedPath || 
                    downloadFolderPath.value?.absolutePath || 
                    downloadFolderPath.value || 
                    '';
    
    // 构建完整的文件夹路径：基础路径 + 大标题 + 视频标题，使用 Windows 路径分隔符
    const folderPath = `${basePath}\\${video.folderName || ''}\\${video.title}`;
    await navigator.clipboard.writeText(folderPath);
    ElMessage.success('已复制文件夹路径');
  } catch (error) {
    console.error('复制路径失败:', error);
    const errorMessage = error.response?.data?.message || error.message || '未知错误';
    ElMessage.error(`复制路径失败: ${errorMessage}`);
  }
};

// 清理文件名中的非法字符（与后端保持一致）
const sanitizeFileName = (fileName) => {
  if (!fileName || fileName.trim() === '') {
    return '未知视频'
  }
  
  // 移除或替换非法字符
  let sanitized = fileName
    .replace(/[\\/:*?"<>|]/g, '_')  // 替换非法字符为下划线
    .replace(/\s+/g, ' ')          // 多个空格替换为单个空格
    .trim()                        // 去除首尾空格
  
  // 限制文件名长度，避免路径过长
  if (sanitized.length > 100) {
    sanitized = sanitized.substring(0, 100) + '...'
  }
  
  // 确保文件名不为空
  if (sanitized === '') {
    sanitized = '未知视频'
  }
  
  return sanitized
}

// 跨平台路径拼接
const joinPath = (basePath, subPath) => {
  if (!basePath || !subPath) return basePath || subPath || ''
  
  // 确保基础路径不以分隔符结尾，子路径不以分隔符开始
  const cleanBasePath = basePath.replace(/[/\\]+$/, '')
  const cleanSubPath = subPath.replace(/^[/\\]+/, '')
  
  // 根据平台选择正确的分隔符
  const separator = navigator.platform.toLowerCase().includes('win') ? '\\' : '/'
  
  return cleanBasePath + separator + cleanSubPath
}

// 统一的文件夹打开逻辑
const openFolderWithFallback = (folderPath, description = '') => {
  try {
    if (window.electronAPI) {
      // Electron环境
      window.electronAPI.openFolder(folderPath)
      ElMessage.success(`已打开${description}文件夹`)
    } else {
      // 浏览器环境，直接显示路径复制对话框
      console.log('浏览器环境无法直接打开文件夹，显示路径复制对话框')
      ElMessage.warning(`无法在浏览器中直接打开${description}文件夹，请复制路径手动打开`)
      fallbackOpenFolderWithMessage(folderPath, description)
    }
  } catch (error) {
    console.error('打开文件夹失败:', error)
    fallbackOpenFolderWithMessage(folderPath, description)
  }
}

// 降级文件夹打开方案（带消息提示）
const fallbackOpenFolderWithMessage = (folderPath, description = '') => {
  console.log(`尝试使用降级方案打开${description}文件夹:`, folderPath)
  
  // 在浏览器环境中，file://协议通常被阻止，直接显示路径信息
  if (!window.electronAPI) {
    // 浏览器环境，直接显示路径复制对话框
    showPathInfoWithDescription(folderPath, description)
    return
  }
  
  // 只在Electron环境中尝试file://协议
  try {
    const fileUrl = 'file:///' + folderPath.replace(/\\/g, '/')
    console.log('构建的文件URL:', fileUrl)
    
    const link = document.createElement('a')
    link.href = fileUrl
    link.style.display = 'none'
    document.body.appendChild(link)
    
    link.click()
    ElMessage.success(`尝试打开${description}文件夹`)
    document.body.removeChild(link)
  } catch (e) {
    console.error('file://协议打开失败:', e)
    // 如果失败，显示路径信息并提供复制功能
    showPathInfoWithDescription(folderPath, description)
  }
}

// 显示路径信息并提供复制功能（带描述）
const showPathInfoWithDescription = (folderPath, description = '') => {
  const message = `
    无法自动打开${description}文件夹。
    
    文件夹路径：${folderPath}
    
    你可以：
    1. 点击"复制路径"按钮复制路径
    2. 手动打开文件管理器并粘贴路径
    3. 或者检查文件夹是否存在
  `
  
  ElMessageBox.confirm(
    message,
    `${description}文件夹路径`,
    {
      confirmButtonText: '复制路径',
      cancelButtonText: '关闭',
      type: 'info',
      showCancelButton: true,
      dangerouslyUseHTMLString: false
    }
  ).then(() => {
    // 复制路径到剪贴板
    navigator.clipboard.writeText(folderPath).then(() => {
      ElMessage.success('路径已复制到剪贴板，请在文件管理器中粘贴')
    }).catch(() => {
      // 降级方案：使用传统的复制方法
      const textArea = document.createElement('textarea')
      textArea.value = folderPath
      document.body.appendChild(textArea)
      textArea.select()
      document.execCommand('copy')
      document.body.removeChild(textArea)
      ElMessage.success('路径已复制到剪贴板，请在文件管理器中粘贴')
    })
  }).catch(() => {
    // 用户取消
  })
}

// 重试下载
const handleRetryDownload = async (video) => {
  try {
    await axios.post(`/api/video/download/retry/${video.id}`)
    ElMessage.success('已开始重新下载')
    await fetchDownloadList()
  } catch (error) {
    console.error('重试失败:', error)
    ElMessage.error('重试失败: ' + (error.response?.data?.message || error.message))
  }
}

// 删除下载任务
const handleDeleteDownload = async (video) => {
  try {
    await axios.delete(`/api/video/download/${video.id}`)
    ElMessage.success('删除成功')
    await fetchDownloadList()
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
  }
}

// 清理已完成的下载
const handleClearCompleted = async () => {
  try {
    await axios.delete('/api/video/download/completed')
    ElMessage.success('清理成功')
    await fetchDownloadList()
  } catch (error) {
    console.error('清理失败:', error)
    ElMessage.error('清理失败: ' + (error.response?.data?.message || error.message))
  }
}

// 清空所有下载
const handleClearAll = async () => {
  try {
    await axios.delete('/api/video/download/clear-all')
    ElMessage.success('清空成功')
    await fetchDownloadList()
  } catch (error) {
    console.error('清空失败:', error)
    ElMessage.error('清空失败: ' + (error.response?.data?.message || error.message))
  }
}

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedDownloads.value = selection
}

// 处理图片加载错误
const handleImageError = (e) => {
  console.log('图片加载失败，使用默认封面:', e.target.src)
  e.target.src = getDefaultCover()
}

// 修改模板中的刷新按钮点击事件
const handleRefresh = () => {
  console.log('点击刷新按钮')
  fetchDownloadList()
}

// 复制下载目录路径
const copyDownloadFolderPath = async () => {
  try {
    const basePath = downloadFolderPath.value?.resolvedPath || 
                    downloadFolderPath.value?.absolutePath || 
                    downloadFolderPath.value || 
                    ''
    if (!basePath) {
      throw new Error('下载目录路径未设置')
    }
    await navigator.clipboard.writeText(basePath)
    ElMessage.success('已复制下载目录路径')
  } catch (error) {
    console.error('复制路径失败:', error)
    ElMessage.error('复制路径失败: ' + (error.response?.data?.message || error.message))
  }
}

// 组件挂载时
onMounted(async () => {
  await fetchDownloadFolderPath()
  await fetchDownloadList()
})

// 组件卸载时
onUnmounted(() => {
  // 组件卸载清理
})

// 在组件卸载时清理
onBeforeUnmount(() => {
  // 组件卸载清理
})

// 暴露方法给父组件
defineExpose({
  fetchDownloadList,
  handleRefresh,
  startDownload: async (videoUrl) => {
    try {
      const response = await axios.post('/api/video/download', { videoUrl })
      const downloadId = response.data
      console.log('开始下载:', downloadId)
      await fetchDownloadList()
    } catch (error) {
      console.error('下载失败:', error)
      ElMessage.error('下载失败: ' + (error.response?.data?.message || error.message))
    }
  }
})
</script>

<style scoped>
.download-manager {
  margin-bottom: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.video-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.video-cover {
  width: 80px;
  height: 45px;
  border-radius: 6px;
  object-fit: cover;
  flex-shrink: 0;
}

.title-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 1;
  min-width: 0;
}

.title-text {
  font-size: 14px;
  line-height: 1.4;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.video-meta {
  display: flex;
  gap: 10px;
  align-items: center;
}

.bvid {
  font-size: 12px;
  color: #409EFF;
  background: #ecf5ff;
  padding: 2px 6px;
  border-radius: 4px;
}

.status-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.error-icon {
  color: #f56c6c;
  cursor: pointer;
}

.download-details {
  width: 100%;
}

.progress-info {
  width: 100%;
  margin-bottom: 8px;
}

.download-stats {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

.stats-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 2px;
}

.stat-label {
  color: #999;
  font-weight: 500;
  min-width: 35px;
}

.stat-value {
  color: #333;
  font-weight: 600;
}

/* 表格行样式 */
:deep(.completed-row) {
  background-color: #f0f9eb;
}

:deep(.failed-row) {
  background-color: #fef0f0;
}

:deep(.downloading-row) {
  background-color: #f5f7fa;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .video-title {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .video-cover {
    width: 100%;
    height: auto;
    max-width: 200px;
  }
}
</style> 